package com.hepinghospital.user.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;

import com.hepinghospital.user.eventbus.Logout;
import com.hepinghospital.user.ui.activity.userinfo.LoginActivity;
import com.rest.exception.ApiException;

import org.greenrobot.eventbus.EventBus;


import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2020/2/9.
 */

public class ToastUtil {

    private static WeakReference<Context> contextWeakReference;

    private static Toast toast;

    public static void init(Context context) {
        contextWeakReference = new WeakReference<>(context);
    }

    /**
     * 默认短时吐司
     */
    public static void showTost(String msg) {
        showTostOne(msg);
    }

    /**
     * 包装一下吐司
     */
    private static void showTostOne(String msg) {
        if (null == contextWeakReference)
            throw new NullPointerException("请调用init在app模块的application中初始化上下文!");
        boolean isMainThread = Looper.myLooper() == Looper.getMainLooper();
        if (isMainThread) {
            show(msg);
        } else {
            Looper.prepare();
            show(msg);
            Looper.loop();
        }
    }

    private static void show(String msg) {
        if (null != contextWeakReference.get()) {
            Toast.makeText(contextWeakReference.get(), msg, Toast.LENGTH_SHORT).show();
        }
    }

    public static void onError(Context context, Throwable e) {
        if (e instanceof ApiException) {
            showToastCenter(context.getApplicationContext(), ((ApiException) e).errorMessage);
            if (((ApiException) e).mErrorCode == 2030007 || ((ApiException) e).mErrorCode == 20200001) {
                EventBus.getDefault().postSticky(new Logout(1));
                context.startActivity(new Intent(context, LoginActivity.class));
            }
        }
    }

    @SuppressLint("ShowToast")
    public static void showToast(Context mContext, String msg) {
        if (toast == null) {
            toast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
        }
        toast.setGravity(Gravity.CENTER, 0, 0); //在屏幕中间
        toast.setText(msg);
        toast.show();
    }

    /**
     * 居中显示的
     */
    @SuppressLint("ShowToast")
    public static void showToastCenter(Context mContext, String msg) {
        if (toast == null) {
            toast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setText(msg);
        toast.show();
    }

    /**
     * 在主线程显示吐司
     */
    public static void showToastOnUIThread(Context mContext, final String msg) {
        Handler handler = new Handler(mContext.getMainLooper());
        handler.post(() -> showToast(mContext, msg));
    }
}
